<template>
  <view class="overflow-h">
    <!-- #ifdef H5 -->
    <image src="https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/login_bg.png" class="login-bg">
    </image>
    <!-- #endif -->
    <!-- #ifndef H5 -->
    <image src="https://gd-hbimg.huaban.com/583cbd8d4c5a86fde133a89729046bc8e08cb1b437853e-vE9VwZ" class="login-bg">
    </image>
    <!-- #endif -->
    <view class="title-box">
      <view>
        <view class="fw-900" style="font-size: 66rpx;transform: skewX(-15deg);">
          潮玩搭子
        </view>
        <view class="fw-900">轻人一起玩的搭子局！</view>
      </view>
    </view>
    <view class="ping-40 pb-30">
      <!-- #ifdef MP-WEIXIN -->
      <view @click="weixinLogin"
            class="flex-dir-row ali-item-cen col-f br-10 w-100 fs-32 bac-col-00b h-90 lh-90 flex-center">
        <view class="mr-10 fs-50"></view>
        <view>微信登录</view>
      </view>
      <!-- #endif -->
      <!-- #ifndef MP-WEIXIN -->
      <view class="flex-dir-row ali-item-cen  br-20 w-100 fs-32 bac-col-fa ping-0-30 flex-center"
            style="height: 80rpx;line-height: 80rpx;">
        <view class="iconfont ic-yonghuming fs-40 col-0 mr-30"></view>
        <input class="flex-1 fs-26" :focus="focusUsername" @blur="focusUsername = false" v-model="username"
               placeholder="请输入手机号/用户名/邮箱" placeholder-class="input-placeholder"/>
      </view>
      <view class="flex-dir-row mt-30 ali-item-cen mb-30 br-20 w-100 fs-32 bac-col-fa ping-0-30 flex-center"
            style="height: 80rpx;line-height: 80rpx;">
        <view class="iconfont ic-mima fs-40 col-0 mr-30"></view>
        <input class="flex-1 fs-26" :focus="focusPassword" @blur="focusPassword = false" v-model="password"
               placeholder="请输入密码" placeholder-class="input-placeholder" type="password" trim="all"/>
      </view>
      <button class="bac-col-00b mt-30 col-f" style="height: 80rpx;line-height: 80rpx;"
              @click="pwdLogin">登录
      </button>
      <view @click="$NavigateTo('/pages/register/register')"
            class="fs-24  flex-dir-row mt-30" style="justify-content: center;">
        <view class="col-b1">还没有账号？</view>
        <view>去注册</view>
      </view>
      <!-- #endif -->
    </view>
    <!-- #ifdef MP-WEIXIN -->
    <view class="ping-40 pt-0">
      <button open-type="getPhoneNumber" @getphonenumber="phoneLogin"
              class="fs-32 br-10 col-54 h-90 lh-90">授权手机号登录
      </button>
    </view>
    <!-- #endif -->

    <!-- 用户信息弹窗 -->
    <wx-user-info-modal v-model="showAuthorizationModal" @updated="updatedUserInfoEvent"></wx-user-info-modal>


  </view>
</template>

<script>
import {
  store,
  mutations
} from '@/utils/store.js'

import WxUserInfoModal
  from '@/uni_modules/tuniaoui-wx-user-info/components/tuniaoui-wx-user-info/tuniaoui-wx-user-info.vue'


export default {
  components: {
    WxUserInfoModal
  },
  data() {
    return {
      password: "",
      username: "",
      showAuthorizationModal: false,
      focusUsername: false,
      focusPassword: false,
      wxCode: '', // 微信登录code
      isLoggedIn: false, // 标记是否已登录成功
      userInfo: null
    }
  },
  methods: {

    // 获取到的用户信息
    async updatedUserInfoEvent(info) {
      console.log('获取到用户信息:', info);
      let avatarUrl = info.avatar;

      try {
        uni.showLoading({
          title: "更新头像中...",
          mask: true
        });

        // 使用自定义上传方法上传头像
        const {upload} = require('@/utils/request.js');
        const uploadResult = await upload('/file/upload', {
          file: avatarUrl
        });
        let avatar = uploadResult.data.url;

        // 调用更新用户信息接口
        const updateData = {
          nickname: info.nickname,
          avatar: avatar,
          id:this.userInfo.id
        };

        console.log('更新用户信息:', updateData);

        // 调用更新用户信息接口
        const result = await this.$auth.updateUserInfo(updateData);

        console.log('用户信息更新成功:', result);

        // 关闭弹窗
        this.showAuthorizationModal = false;

        // 显示成功提示
        this.$Toast('用户信息更新成功');

        // 跳转到首页
        setTimeout(() => {
          this.loginSuccess();
        }, 1000);

        uni.hideLoading();
      } catch (error) {
        uni.hideLoading();
        console.error('用户信息更新失败:', error);
        this.$Toast(error.message || '用户信息更新失败，请重试');
        // 更新失败时关闭弹窗
        this.showAuthorizationModal = false;
      }
    },

    // 微信登录
    async weixinLogin() {
      // #ifdef MP-WEIXIN
      try {
        uni.showLoading({
          title: "获取登录凭证...",
          mask: true
        });

        // 先获取微信登录code
        const loginRes = await uni.login({
          provider: 'weixin'
        });

        console.log('微信登录结果:', loginRes);

        if (loginRes[1] && loginRes[1].code) {
          this.wxCode = loginRes[1].code;
          console.log('获取到微信code:', this.wxCode);

          // 先用code登录获取用户信息
          await this.loginWithCode();
        } else {
          throw new Error('获取微信登录凭证失败');
        }
      } catch (error) {
        uni.hideLoading();
        console.error('微信登录失败:', error);
        this.$Toast(error.message || '微信登录失败，请重试');
      }
      // #endif
    },

    // 使用code登录
    async loginWithCode() {
      try {
        uni.showLoading({
          title: "登录中...",
          mask: true
        });

        // 调用后台登录接口，只传code
        const loginData = {
          wxCode: this.wxCode,
          loginType: 'weixin'
        };

        console.log('发送登录请求:', loginData);

        // 调用登录接口
        const result = await this.$auth.login(loginData);
        console.log('登录返回结果:', result);

        // 检查登录是否成功
        if (result && (result.code === 200 || result.success)) {
          // 获取用户信息，可能在result.data或result.userInfo中
          const userInfo = result.data.userInfo || {};
          this.userInfo = userInfo;
          const hasAvatar = userInfo.avatar && userInfo.avatar.trim() !== '';

          console.log('登录成功，用户头像检查:', {
            userInfo: userInfo,
            avatar: userInfo.avatar,
            hasAvatar: hasAvatar
          });

          if (hasAvatar) {
            // 已有头像，直接登录成功
            this.isLoggedIn = true;
            uni.hideLoading();
            this.$Toast('登录成功');
            setTimeout(() => {
              this.loginSuccess();
            }, 1000);
          } else {
            // 没有头像，显示授权弹窗
            this.isLoggedIn = true; // 标记已登录，只是需要完善信息
            uni.hideLoading();
            console.log('用户没有头像，显示授权弹窗');
            this.showAuthorizationModal = true;
          }
        } else {
          throw new Error(result.message || result.msg || '登录失败');
        }
      } catch (error) {
        uni.hideLoading();
        console.error('登录失败:', error);
        this.$Toast(error.message || '登录失败，请重试');
      }
    },

    // 手机号登录
    async phoneLogin(e) {
      // #ifdef MP-WEIXIN
      try {
        this.$Loading('登录中')
        if (e.detail?.code) {
          const result = await this.$auth.login({
            type: 'phone',
            phoneCode: e.detail.code
          })

          this.$Toast('登录成功')
          setTimeout(() => {
            this.loginSuccess()
          }, 1000)
        }
      } catch (error) {
        console.error('手机号登录失败:', error)
        this.$Toast(error.message || '登录失败')
      } finally {
        uni.hideLoading()
      }
      // #endif
    },

    // 密码登录
    async pwdLogin() {
      if (!this.username.length) {
        this.focusUsername = true
        return this.$Toast('请输入手机号/用户名/邮箱')
      }
      if (!this.password.length) {
        this.focusPassword = true
        return this.$Toast('请输入密码')
      }

      try {
        this.$Loading('登录中')

        let data = {
          password: this.password
        }

        if (/^1\d{10}$/.test(this.username)) {
          data.mobile = this.username
        } else if (/@/.test(this.username)) {
          data.email = this.username
        } else {
          data.username = this.username
        }
        data.loginType = 'app'

        const result = await this.$auth.login(data)
        this.$Toast('登录成功')
        setTimeout(() => {
          this.loginSuccess()
        }, 1000)

      } catch (error) {
        console.error('密码登录失败:', error)
        this.$Toast(error.message || '登录失败')
      } finally {
        uni.hideLoading()
      }
    },

    // 登录成功处理
    loginSuccess() {
      // 跳转到首页或者返回上一页
      const pages = getCurrentPages()
      console.log("pages.length", pages.length)

      if (pages.length > 1) {
        uni.navigateBack()
      } else {
        console.log("relauch1111")
        console.log("relauch1111")
        uni.reLaunch({
          url: '/pages/index/index'
        })
      }

    }
  }
}
</script>

<style lang="scss">
.title-box {
  margin-top: 700rpx;
  padding: 40rpx;
}

@keyframes rotateAnimation {
  0% {
    transform: rotate(0deg);
  }

  25% {
    transform: rotate(10deg);
  }

  50% {
    transform: rotate(0deg);
  }

  75% {
    transform: rotate(-10deg);
  }

  100% {
    transform: rotate(0deg);
  }
}

.login-bg {
  width: 1200rpx;
  height: 1200rpx;
  position: fixed;
  top: -365rpx;
  right: -420rpx;
  z-index: -1;
  animation: rotateAnimation 50s linear infinite;
}

.input-placeholder {
  color: #c0c0c0;
}
</style>
